import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

public class RestApiClientJDK8 {

    public static void main(String[] args) {
        String urlString = "https://jsonplaceholder.typicode.com/posts/1";

        try {
            // 创建 URL 和 HttpURLConnection
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("GET");

            // 读取响应数据
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 打印原始响应
            System.out.println("响应内容：" + response.toString());

            // 解析 JSON
            JSONObject jsonObject = new JSONObject(response.toString());

            // 提取字段
            int userId = jsonObject.getInt("userId");
            int id = jsonObject.getInt("id");
            String title = jsonObject.getString("title");
            String body = jsonObject.getString("body");

            // 输出解析后的内容
            System.out.println("userId: " + userId);
            System.out.println("id: " + id);
            System.out.println("title: " + title);
            System.out.println("body: " + body);

            // 关闭连接
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
